import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/order.dart';
import '../services/product_service.dart';

class OrderService {
  final dbHelper = DatabaseHelper.instance;
  final ProductService _productService = ProductService();

  Future<int> insertOrder(Order order) async {
    Database db = await dbHelper.database;

    // 使用事务确保数据一致性
    return await db.transaction((txn) async {
      // 1. 创建订单
      int orderId = await txn.insert('orders', order.toMap());

      // 2. 创建订单项目并减少库存
      if (order.items != null && order.items!.isNotEmpty) {
        for (var item in order.items!) {
          // 添加订单项
          await txn.insert('order_items', {
            'orderId': orderId,
            'productId': item.productId,
            'quantity': item.quantity,
            'price': item.price,
          });

          // 在事务内直接减少库存
          // 先获取当前商品
          List<Map<String, dynamic>> productMaps = await txn.query(
            'products',
            where: 'id = ?',
            whereArgs: [item.productId],
          );

          if (productMaps.isEmpty) {
            throw Exception('商品不存在');
          }

          int currentStock = productMaps.first['stock'];

          // 检查库存是否足够
          if (currentStock < item.quantity) {
            throw Exception('商品库存不足');
          }

          // 更新库存
          int newStock = currentStock - item.quantity;
          int result = await txn.update(
            'products',
            {'stock': newStock},
            where: 'id = ?',
            whereArgs: [item.productId],
          );

          if (result <= 0) {
            throw Exception('更新库存失败');
          }
        }
      }

      return orderId;
    });
  }

  Future<int> updateOrderStatus(int id, String status) async {
    Database db = await dbHelper.database;
    return await db.update(
      'orders',
      {'status': status},
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<Order?> getOrderById(int id) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'orders',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      Order order = Order.fromMap(maps.first);

      // Get order items
      List<Map<String, dynamic>> itemMaps = await db.query(
        'order_items',
        where: 'orderId = ?',
        whereArgs: [id],
      );

      List<OrderItem> items = List.generate(
        itemMaps.length,
        (i) => OrderItem.fromMap(itemMaps[i])
      );

      return Order(
        id: order.id,
        userId: order.userId,
        totalAmount: order.totalAmount,
        status: order.status,
        orderDate: order.orderDate,
        items: items,
      );
    }
    return null;
  }

  Future<List<Order>> getOrdersByUserId(int userId) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'orders',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'orderDate DESC',
    );

    return List.generate(maps.length, (i) => Order.fromMap(maps[i]));
  }

  Future<List<Order>> getAllOrders() async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'orders',
      orderBy: 'orderDate DESC',
    );

    return List.generate(maps.length, (i) => Order.fromMap(maps[i]));
  }
}
